from flask import Flask, request, render_template_string, send_from_directory
import os
import subprocess
import time
import re
import json
from flask import jsonify

app = Flask(__name__)

# 存储消息
messages = []

# 文件路径配置
TARGET_FILE = "/home/orangepi/Desktop/orangepi/heron_process_image_new_module.py"
PROCESS_NAME = "heron_process_image_new_module.py"
CONFIG_FILE_PATH = "/home/orangepi/Desktop/orangepi/heron_process_image_new_module.py"
CAPTURED_IMAGE_PATH = "/home/orangepi/Desktop/orangepi/image.jpg"


STATE_FILE = "state.json"

def get_initial_state():
    print("state file", STATE_FILE)
    if os.path.exists(STATE_FILE):
        with open(STATE_FILE, "r") as f:
            return json.load(f).get("flag", False)
    return False

def update_state(value):
    with open(STATE_FILE, "w") as f:
        json.dump({"flag": value}, f)
    return value

#mute_state = get_initial_state()

# 读取当前配置值
def read_config_values():
    conf_num = 0.5  # 默认值
    ratio_num = 0.8  # 默认值
    
    if os.path.exists(CONFIG_FILE_PATH):
        with open(CONFIG_FILE_PATH, "r") as f:
            content = f.read()
            
        conf_match = re.search(r"conf_num\s*=\s*([0-9.]+)", content)
        ratio_match = re.search(r"ratio_num\s*=\s*([0-9.]+)", content)
        
        if conf_match:
            conf_num = float(conf_match.group(1))
        if ratio_match:
            ratio_num = float(ratio_match.group(1))
    
    return conf_num, ratio_num

# 新增功能：修改文件中的 play_sound 值
def update_play_sound_file(state):
    """修改文件中的 play_sound = True/False"""
    try:
        with open(TARGET_FILE, 'r') as f:
            content = f.read()


        print("updating",mute_state)
        print("state", state)
        
        # 替换所有 play_sound = True/False
        content = re.sub(r'play_sound\s*=\s*(True|False)', 
                        f'play_sound = {str(state)} ', 
                        content)

        with open(CONFIG_FILE_PATH, 'w') as f:
            f.write(content)
    except Exception as e:
        print(f"[ERROR] 修改文件失败: {e}")

# 更新配置值
def update_config_values(conf_num, ratio_num):
    if not os.path.exists(CONFIG_FILE_PATH):
        return False
        
    with open(CONFIG_FILE_PATH, "r") as f:
        content = f.read()
    
    # 替换 conf_num
    content = re.sub(r"conf_num\s*=\s*[0-9.]+", f"conf_num = {conf_num}", content)
    # 替换 ratio_num
    content = re.sub(r"ratio_num\s*=\s*[0-9.]+", f"ratio_num = {ratio_num}", content)
    
    with open(CONFIG_FILE_PATH, "w") as f:
        f.write(content)
    
    return True

# 终止 heron_process_image_new_module.py 进程
def kill_script_process():
    try:
        # 查找并终止进程（根据文件名匹配）
        subprocess.run(["pkill", "-f", "heron_process_image_new_module.py"], check=True)
        return True
    except subprocess.CalledProcessError:
        return False

@app.route('/captured_image')
def send_captured_image():
    return send_from_directory(
        os.path.dirname(CAPTURED_IMAGE_PATH),
        os.path.basename(CAPTURED_IMAGE_PATH)
    )

# 新增功能：处理 Mute/Unmute 按钮
@app.route('/toggle_mute', methods=['POST'])
def toggle_mute():

    global mute_state 
    mute_state = get_initial_state()
    # 杀死旧进程
    kill_script_process()

    # 切换状态
    print("1", mute_state)
    mute_state = not mute_state
    print("2", mute_state)
    # 更新文件中的 play_sound
    update_play_sound_file(mute_state)
    update_state(mute_state)
    return jsonify(state='unmute' if mute_state else 'mute')

@app.route('/')
def index():
    current_conf, current_ratio = read_config_values()
    
    return render_template_string('''
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Heron Driver Control Panel</title>
            <style>
                * {
                    box-sizing: border-box;
                }
                
                body {
                    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                    margin: 0;
                    padding: 0;
                    background-color: #f5f7fa;
                    color: #333;
                }
                
                .container {
                    max-width: 1000px;
                    margin: 2rem auto;
                    padding: 1.5rem;
                    background-color: #ffffff;
                    border-radius: 12px;
                    box-shadow: 0 4px 20px rgba(0,0,0,0.05);
                }
                
                h1 {
                    text-align: center;
                    color: #2c3e50;
                    margin-bottom: 2rem;
                }
                
                .control-section {
                    display: flex;
                    flex-wrap: wrap;
                    gap: 2rem;
                    justify-content: center;
                    margin-bottom: 2rem;
                }
                
                .config-card {
                    flex: 1 1 300px;
                    padding: 1.5rem;
                    background-color: #f8f9fa;
                    border-radius: 10px;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.03);
                }
                
                .config-card h3 {
                    margin-top: 0;
                    color: #3498db;
                }
                
                .slider-container {
                    margin-top: 1rem;
                    position: relative;
                }
                
                input[type="range"] {
                    width: 100%;
                    height: 10px;
                    -webkit-appearance: none;
                    background: #ddd;
                    border-radius: 5px;
                    outline: none;
                    cursor: pointer;
                }
                
                input[type="range"]::-webkit-slider-thumb {
                    -webkit-appearance: none;
                    appearance: none;
                    width: 20px;
                    height: 20px;
                    border-radius: 50%;
                    background: #3498db;
                    cursor: pointer;
                }
                
                .slider-value {
                    text-align: center;
                    margin-top: 0.5rem;
                    font-weight: bold;
                }
                
                .button-group {
                    display: flex;
                    gap: 1rem;
                    justify-content: center;
                    margin-top: 2rem;
                }
                
                button {
                    padding: 1rem 2rem;
                    background-color: #3498db;
                    color: white;
                    border: none;
                    border-radius: 8px;
                    font-size: 1rem;
                    cursor: pointer;
                    transition: all 0.3s ease;
                }
                
                button:hover {
                    background-color: #2980b9;
                    transform: translateY(-2px);
                }
                
                .image-container {
                    margin-top: 2rem;
                    text-align: center;
                }
                
                .image-container img {
                    max-width: 100%;
                    height: auto;
                    display: block;
                    margin: 0 auto;
                    border-radius: 10px;
                    transition: transform 0.3s ease;
                }
                
                .image-container img:hover {
                    transform: scale(1.02);
                }
                
                @media (max-width: 600px) {
                    .button-group {
                        flex-wrap: wrap;
                        gap: 1rem;
                    }

                    .button-group button {
                        width: 100%;
                        padding: 0.8rem 1rem;
                        font-size: 0.95rem;
                    }

                    .config-card {
                        flex: 1 1 100%;
                    }

                    .container {
                        margin: 1rem;
                        padding: 1rem;
                    }
                }
            </style>
        </head>
        <body>
            <div class="container">
                <h1>Heron Dispersion Device Control Panel</h1>
                
                <!-- 控制面板 -->
                <div class="control-section">
                    <!-- conf_num 控制 -->
                    <div class="config-card">
                        <h3>Confidence</h3>
                        <div class="slider-container">
                            <input type="range" id="confSlider" min="0.1" max="1.0" step="0.1" value="{{ current_conf }}">
                            <div class="slider-value" id="confValue">{{ current_conf }}</div>
                        </div>
                    </div>
                    
                    <!-- ratio_num 控制 -->
                    <div class="config-card">
                        <h3>Ratio</h3>
                        <div class="slider-container">
                            <input type="range" id="ratioSlider" min="1.0" max="3.0" step="0.1" value="{{ current_ratio }}">
                            <div class="slider-value" id="ratioValue">{{ current_ratio }}</div>
                        </div>
                    </div>
                </div>
                
                <!-- 操作按钮 -->
                <div class="button-group">
                    <button onclick="saveConfig()">Save & Restart</button>
                </div>
                
                <!-- 设备控制按钮 -->
                <div class="button-group">
                    <button onclick="post1Request()">Send Audio Alarm</button>
                    <button onclick="post2Request()">Turn On Laser</button>
                    <button onclick="post3Request()">Turn Off Laser</button>
                    <button id="muteButton">{{ "Unmute" if not mute_state else "Mute" }}</button>
                    <button onclick="post4Request()">Refresh Camera Image</button>
                </div>
                
                <!-- 图片展示 -->
                <div class="image-container">
                    <h3>Camera Image:</h3>
                    <div id="postResult4"></div>
                </div>
            </div>

            <script>
                // Mute/Unmute 按钮事件
                document.getElementById('muteButton').addEventListener('click', function() {
                    fetch('/toggle_mute', {
                        method: 'POST'
                    }).then(response => response.json())
                      .then(data => {
                          this.textContent = data.state === 'mute' ? 'Unmute' : 'Mute';
                      });
                });

                // 实时更新滑块显示值
                document.getElementById('confSlider').addEventListener('input', function() {
                    document.getElementById('confValue').textContent = this.value;
                });
                
                document.getElementById('ratioSlider').addEventListener('input', function() {
                    document.getElementById('ratioValue').textContent = this.value;
                });

                // 保存配置并重启
                async function saveConfig() {
                    const confValue = document.getElementById('confSlider').value;
                    const ratioValue = document.getElementById('ratioSlider').value;
                    
                    try {
                        const response = await fetch('/api/update_config', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                conf_num: parseFloat(confValue),
                                ratio_num: parseFloat(ratioValue)
                            })
                        });
                        
                        const result = await response.json();
                        if (result.success) {
                            alert('Configuration updated successfully!');
                        } else {
                            alert('Failed to update configuration: ' + result.message);
                        }
                    } catch (error) {
                        alert('Error: ' + error.message);
                    }
                }
                
                // 通用POST请求函数
                function postRequest(url, message = 'Client request') {
                    return fetch(url, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            message: message,
                            timestamp: new Date().toISOString()
                        }),
                    });
                }

                // 具体请求函数
                function post1Request() {
                    postRequest('/api/post1').then(response => {
                        return response.text();
                    }).then(data => {
                        document.getElementById('postResult1').innerHTML = data;
                    });
                }

                function post2Request() {
                    postRequest('/api/post2').then(response => {
                        return response.text();
                    }).then(data => {
                        document.getElementById('postResult2').innerHTML = data;
                    });
                }

                function post3Request() {
                    postRequest('/api/post3').then(response => {
                        return response.text();
                    }).then(data => {
                        document.getElementById('postResult3').innerHTML = data;
                    });
                }

                function post4Request() {
                    postRequest('/api/post4').then(response => {
                        return response.text();
                    }).then(data => {
                        document.getElementById('postResult4').innerHTML = data;
                    });
                }
            </script>
        </body>
        </html>
    ''', current_conf=current_conf, current_ratio=current_ratio)

@app.route('/api/update_config', methods=['POST'])
def update_config():
    data = request.get_json()
    conf_num = data.get('conf_num', 0.5)
    ratio_num = data.get('ratio_num', 0.8)
    
    try:
        if not update_config_values(conf_num, ratio_num):
            return {'success': False, 'message': 'Failed to update config file'}
        
        if not kill_script_process():
            return {'success': False, 'message': 'Failed to restart process'}
            
        return {'success': True, 'message': 'Configuration updated successfully'}
    except Exception as e:
        return {'success': False, 'message': f'Error: {str(e)}'}

# 以下保持原有API接口不变
@app.route('/api/post1', methods=['POST'])
def handle_post1():
    import requests
    from requests.auth import HTTPDigestAuth

    url = 'http://192.168.50.187/digest/frmAudioSpeech'
    headers = {
        'Content-Type': 'application/json',
        'User-Agent': 'curl/4.7.1',
        'Cache-Control': 'no-cache',
        'Postman-Token': 'cfdf0937-f7a5-4b79-8c39-42eb232d4c0b',
    }
    data = {
        "Type": 1,
        "Dev": 1,
        "Ch": 1,
        "Data": {
            "DetectType": 9,
            "AudioSelected": 1
        }
    }
    username = 'admin'
    password = '123456'

    response = requests.post(url, json=data, headers=headers, auth=HTTPDigestAuth(username, password))
    return f'POST1 request received. Status: {response.status_code}'

@app.route('/api/post2', methods=['POST'])
def handle_post2():
    import requests
    from requests.auth import HTTPDigestAuth

    url = 'http://192.168.50.187/digest/frmAlarmOut'
    headers = {
        'Content-Type': 'application/json',
        'User-Agent': 'curl/4.7.1',
        'Cache-Control': 'no-cache',
        'Postman-Token': 'cfdf0937-f7a5-4b79-8c39-42eb232d4c0b',
    }
    data = {
        "Type": 1,
        "Ch": 1,
        "Dev": 1,
        "Data": {
            "AlarmCh": 1,
            "AlarmType": 1,
            'SelfDefinedDelay': 5,
            'AlarmOutDelay': 2
        },
    }
    username = 'admin'
    password = '123456'

    response = requests.post(url, json=data, headers=headers, auth=HTTPDigestAuth(username, password))
    return f'POST2 request received. Status: {response.status_code}'

@app.route('/api/post3', methods=['POST'])
def handle_post3():
    import requests
    from requests.auth import HTTPDigestAuth

    url = 'http://192.168.50.187/digest/frmAlarmOut'
    headers = {
        'Content-Type': 'application/json',
        'User-Agent': 'curl/4.7.1',
        'Cache-Control': 'no-cache',
        'Postman-Token': 'cfdf0937-f7a5-4b79-8c39-42eb232d4c0b',
    }
    data = {
        "Type": 1,
        "Ch": 1,
        "Dev": 1,
        "Data": {
            "AlarmCh": 1,
            "AlarmType": 0,
            'SelfDefinedDelay': 5,
            'AlarmOutDelay': 2
        },
    }
    username = 'admin'
    password = '123456'

    response = requests.post(url, json=data, headers=headers, auth=HTTPDigestAuth(username, password))
    return f'POST3 request received. Status: {response.status_code}'

@app.route('/api/post4', methods=['POST'])
def handle_post4():
    import time
    import requests
    from requests.auth import HTTPDigestAuth
    from PIL import Image
    from io import BytesIO

    headers = {
        'Content-Type': 'application/json',
        'User-Agent': 'curl/4.7.1',
        'Cache-Control': 'no-cache',
        'Postman-Token': 'cfdf0937-f7a5-4b79-8c39-42eb232d4c0b',
    }
    username = 'admin'
    password = '123456'
    camera_ip = "192.168.50.187"

    url = 'http://' + camera_ip + '/digest/CaptureV2'
    data = {
        "Type": 1,
        "Ch": 1,
        "Dev": 1,
        "Data": {
            "DataType": 0,
            "StreamNo": 0
        }
    }

    response = requests.post(url, json=data, headers=headers, auth=HTTPDigestAuth(username, password))

    image_bytes = BytesIO(response.content)
    image = Image.open(image_bytes)
    image.save(CAPTURED_IMAGE_PATH)
    
    return f'''
        <div>
            <p>Image captured successfully! Status code: {response.status_code}</p>
            <img src="/captured_image?t={time.time()}" 
                 alt="Latest Capture" 
                 style="max-width: 100%; height: auto;">
        </div>
    '''

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
